var CreateSupplyOrder = function () {
  var template = /* html */ `
    <div class="create-supply-order" v-loading.fullscreen.lock="loading">
      <div>
        <el-form inline size="medium">
          <el-form-item label="订单编号">
            <filter-select style="width:200px" v-model="orderId" :options="orderList" value-field="orderId" label-field="orderId"
              popper-class="orderSelectPopover" :filter-method="orderFilterMehod">
              <template slot="item" slot-scope="scope">
                <div class="order-procedure-select-item">
                  <span style="width:145px;">{{scope.option.orderId}}</span>
                  <span style="min-width:145px;">{{scope.option.companyOrderId}}</span>
                  <span style="min-width:100px;">{{scope.option.factoryId}}</span>
                  <span style="min-width:50px;">{{scope.option.customerId}}</span>
                </div>
              </template>
            </filter-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchData">查询</el-button>
            <el-button v-if="supplyOrderList!==null" type="primary" @click="createOrder">生成申补单</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="create-order-table-div">
        <div v-if="supplyOrderList===null" class="no-data">
          <div>请选择订单编号查询相应的订单数据</div>
        </div>
        <template v-else>
          <el-table border stripe fit default-expand-all :data="supplyOrderList" style="width:100%" height="parent" row-key="id" @selection-change="toSelectSupplyOrder"
            :span-method="spanMethod" :row-class-name="getRowClassName">
            <el-table-column sortable label="订单编号" prop="orderId" column-key="personLiable" min-width="170px" header-align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.rowType!=='personLiable'">{{scope.row.orderId}}</span>
                <div v-else style="width:calc(100% - 16px)">
                  <person-liable-show :order="scope.row" @btn-click="resetPersonList"></person-liable-show>
                </div>
              </template>
            </el-table-column>
            <el-table-column sortable label="公司订单编号" prop="compnyOrderId" min-width="140px" header-align="center"></el-table-column>
            <el-table-column sortable label="工厂型号" prop="factoryId" min-width="120px" header-align="center"></el-table-column>
            <el-table-column sortable label="客户型号" prop="coustomId" min-width="120px" header-align="center"></el-table-column>
            <el-table-column sortable label="订单序号" prop="rowIndex" min-width="100px" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.rowIndex===-1?globalConfig.orderDefaultRowIndex:scope.row.rowIndex}}</span>
              </template>
            </el-table-column>
            <el-table-column sortable label="供应商" prop="providerName" min-width="120px" header-align="center"></el-table-column>
            <el-table-column sortable label="物料名称" prop="materialName" min-width="120px" header-align="center"></el-table-column>
            <el-table-column sortable label="物料类型" prop="materialType" min-width="100px" header-align="center"></el-table-column>
            <el-table-column sortable label="编号" prop="color" min-width="100px" header-align="center"></el-table-column>
            <el-table-column sortable label="描述" prop="colorDescription" min-width="120px" header-align="center"></el-table-column>
            <el-table-column sortable label="规格" prop="model" min-width="100px" header-align="center"></el-table-column>
            <el-table-column sortable label="单价" prop="unitPrice" min-width="100px" align="center"></el-table-column>
            <el-table-column sortable label="单位" prop="unit" min-width="100px" align="center"></el-table-column>
            <el-table-column label="申补类型" min-width="130px" header-align="center">
              <template slot-scope="scope" v-if="scope.row.hasCheck">
                <el-select class="table-input" v-model="scope.row.type" size="mini" @change="typeChange(scope.row)">
                  <el-option v-for="type in typeList" :key="'type_'+type.value" :value="type.value" :label="type.label"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="申补人" min-width="150px" header-align="center">
              <template slot-scope="scope" v-if="scope.row.hasCheck">
                <table-select filterable v-model="scope.row.createUser" :options="createUserList" value-key="id" value-field="id" label-field="name">
                </table-select>
              </template>
            </el-table-column>
            <el-table-column label="申补数量" min-width="130px" header-align="center">
              <template slot-scope="scope" v-if="scope.row.hasCheck">
                <el-input-number is-decimal-zero class="table-input" v-model="scope.row.applyCount" size="mini" :controls="false" :min="0" :precision="2">
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="申补原因" min-width="160px" header-align="center">
              <template slot-scope="scope" v-if="scope.row.hasCheck">
                <el-input class="table-input" v-model="scope.row.applyReason" size="mini"></el-input>
              </template>
            </el-table-column>
            <el-table-column type="selection" width="40px" align="center" fixed="right" :selectable="selectable"></el-table-column>
          </el-table>
        </template>
      </div>

      <el-dialog title="设置责任人" :visible.sync="openDialog" top="10vh" width="600px" @closed="selectSupplyOrder=null">
        <div style="height:calc(80vh - 54px);overflow:auto">
          <person-liable-setting v-if="openDialog" :order="selectSupplyOrder" :dropdown-option="dropdownOption" @setting-success="settingSuccess">
          </person-liable-setting>
        </div>
      </el-dialog>
    </div>
  `;

  return {
    mixins: [supplyOrderMixin('create')],

    data: function () {
      return {
        loading: false,
        orderId: '',
        orderList: [],
        supplyOrderList: null,
        selectSupplyOrderList: [],
        typeList: i18n.getDropDown('materialSupplyOrder.orderType', [1, 2]),
        createUserList: [],
        openDialog: false,
        selectSupplyOrder: null,
        dropdownOption: {},
        user: null
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.setOrderList(),
        this.setCreateUserList(),
        this.setUser()
      ]).then(function () {
        self.loading = false;
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      setOrderList: function () {
        var self = this;
        return ajaxRequest('weiXin/getOrderList').then(function (orderList) {
          self.orderList = orderList;
          return orderList;
        });
      },

      //设置可选申补人
      setCreateUserList: function () {
        var self = this;
        return ajaxRequest('dingTalk/askForApprover').then(function (createUserList) {
          createUserList = _.map(createUserList, function (createUser) {
            return {
              id: String(createUser.id),
              name: createUser.personName
            };
          });
          self.createUserList = createUserList;
          return createUserList;
        });
      },

      setUser: function () {
        var self = this;
        return SysUtil.getUser().then(function (user) {
          self.user = user;
          return user;
        });
      },

      orderFilterMehod: function (query, option) {
        var filterParams = ['orderId', 'companyOrderId', 'factoryId', 'customerId'];
        for (var i = 0; i < filterParams.length; i++) {
          var filterParam = filterParams[i];
          var value = _.get(option, filterParam, '');
          if (value === null) {
            value = '';
          }
          if (typeof value === 'string') {
            value = value.toLowerCase();
          }
          if (value.indexOf(query) !== -1) {
            return true;
          }
        }
        return false;
      },

      searchData: function () {
        var orderId = this.orderId;
        this.loading = true;
        var self = this;
        ajaxRequest('applyRepairForm/getOrderInfoDetail', {
          orderId: orderId
        }).then(function (supplyOrderList) {
          var user = self.user;
          var createUserList = self.createUserList;
          var createUser = _.find(createUserList, {
            id: user.userId
          });
          if (createUser === undefined) {
            createUser = '';
          }

          for (var i = 0; i < supplyOrderList.length; i++) {
            var supplyOrder = supplyOrderList[i];
            supplyOrder.id = SysUtil.getId();
            supplyOrder.type = '';
            supplyOrder.applyCount = undefined;
            supplyOrder.applyReason = '';
            supplyOrder.createUser = _.cloneDeep(createUser);

            var materialCode = supplyOrder.materialCode;
            if (typeof materialCode === 'string') {
              materialCode = materialCode.trim();
            }
            var hasCheck = !SysUtil.isEmpty(materialCode);
            if (hasCheck) {
              supplyOrder.children = [];
            }

            supplyOrder.hasCheck = hasCheck;
          }
          self.supplyOrderList = supplyOrderList;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      typeChange: function (order) {
        var type = order.type;
        if (type === 2) {
          order.children = [{
            id: SysUtil.getId(),
            rowType: 'personLiable',
            parentId: order.id,
            personLiableList: [],
          }];
          this.selectSupplyOrder = order;
          this.openDialog = true;
        } else {
          order.children = [];
        }
      },

      resetPersonList: function (id) {
        var supplyOrderList = this.supplyOrderList;
        var supplyOrder = _.find(supplyOrderList, {
          id: id
        });
        this.selectSupplyOrder = supplyOrder;
        this.openDialog = true;
      },

      settingSuccess: function () {
        this.openDialog = false;
      },

      selectable: function (row) {
        return row.hasCheck;
      },

      toSelectSupplyOrder: function (supplyOrderList) {
        this.selectSupplyOrderList = supplyOrderList;
      },

      createOrder: function () {
        var selectSupplyOrderList = this.selectSupplyOrderList;
        if (selectSupplyOrderList.length === 0) {
          this.$alert('请选择需要生成申补单的订单数据', '信息');
          return;
        }

        var fields = ["orderId", "rowIndex", "materialCode", "materialType", "unitPrice", "type", "applyCount", "applyReason"];
        var postDataList = [];
        for (var i = 0; i < selectSupplyOrderList.length; i++) {
          var supplyOrder = selectSupplyOrderList[i];
          if (!this.checkValid(supplyOrder)) {
            return;
          }

          var persons = [];
          if (supplyOrder.type === 2) {
            var persons = supplyOrder.children[0].personLiableList;
            persons = _.map(persons, function (person) {
              var share = person.share;
              return {
                userId: person.id,
                userName: `${person.name}:${share}%`,
                share: share
              };
            });
          }

          var createUser = supplyOrder.createUser;
          var postData = {
            createUserId: createUser.id,
            personLiableList: persons
          };
          SysUtil.setPostData(postData, supplyOrder, fields, false, true);

          postDataList.push(postData);
        }

        this.loading = true;
        var self = this;
        ajaxRequest('applyRepairForm/createApplyRepairForm', {
          applyArray: JSON.stringify(postDataList)
        }).then(function (msg) {
          self.$alert('成功生成申补单', '信息', {
            callback: function () {
              self.searchData();
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      checkValid: function (supplyOrder) {
        var fields = ['type', 'createUser', 'applyCount', 'applyReason'];
        var code = CheckVaildUtil.checkNullField(fields, supplyOrder);
        if (code !== '') {
          var msg = i18n.getMsg(`materialSupplyOrder.error.${code}`);
          this.$alert(msg, '信息');
          return false;
        }

        if (supplyOrder.applyCount === 0) {
          var msg = i18n.getMsg('materialSupplyOrder.error.applyCountZero');
          this.$alert(msg, '信息');
          return false;
        }

        if (supplyOrder.type === 2) {
          var persons = supplyOrder.children[0].personLiableList;
          if (persons.length === 0) {
            var msg = i18n.getMsg('materialSupplyOrder.error.personLiableList');
            this.$alert(msg, '信息');
            return false;
          }
        }
        return true;
      }
    },

    components: {
      FilterSelect: FilterSelect,
      PersonLiableSetting: PersonLiableSetting,
      PersonLiableShow: PersonLiableShow,
      TableSelect: TableSelect
    },

    template: template
  };
}();
